package online_handler

import (
	"fmt"
	"peilian-api/app/global/bind"
	"peilian-api/app/global/common"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/app/services/user_service"
	"peilian-api/utils/format"
	"peilian-api/utils/tools"
	"time"

	"github.com/gin-gonic/gin"
)

func DynamicCodeHandler(ctx *gin.Context) {
	var cr model.CodeMailReq
	if err := bind.ShouldBinding(ctx, &cr); err != nil {
		format.NewResponseJson(ctx).Err(30001, err.Error())
		return
	}
	if err := user_service.SendMailDynamicCode(ctx, cr.Email); err != nil {
		format.NewResponseJson(ctx).Err(err.Code, err.Err.Error())
		return
	}
	format.NewResponseJson(ctx).SuccessObj(struct{}{})
}

// 带图片的验证码
func GetCaptcha(ctx *gin.Context) {
	var cr model.CaptchaRequest
	if err := bind.ShouldBinding(ctx, &cr); err != nil {
		format.NewResponseJson(ctx).Err(30001, err.Error())
		return
	}
	data := tools.GenerateCaptcha()
	// 将数据缓存起来进行验证, 无需关注失败
	variable.DB.Redis.Set(fmt.Sprintf(common.RedisCaptchaCodeKey, cr.Time, cr.Rand), data.Text, 5*time.Minute)

	s := model.CaptChaResponse{}
	s.Code = data.Text
	s.Img = data.EncodeB64string()
	format.NewResponseJson(ctx).SuccessObj(s)
}
